package com.lekang.le.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lekang.ZcqEntity.NursingCancelDTO;
import com.lekang.ZcqEntity.NursingDetailDTO;
import com.lekang.ZcqEntity.NursingExecuteRecord;
import com.lekang.ZcqEntity.NursingOrderVO;
import com.lekang.le.mapper.NursingJobMapper;
import com.lekang.le.service.NursingJobService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

@Service
public class NursingJobServiceImpl implements NursingJobService {
    @Resource
    private NursingJobMapper nursingJobMapper;

    @Override
    public PageInfo<NursingOrderVO> list(Integer pageNum, Integer pageSize, String oldName, String nurseName, String item, List<String> timeRange, String status) {
        PageHelper.startPage(pageNum, pageSize);
        LocalDateTime start = null;
        LocalDateTime end = null;
        if (timeRange != null && timeRange.size() == 2) {
            String s = timeRange.get(0);
            String e = timeRange.get(1);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate startDate;
            LocalDate endDate;
            startDate = LocalDate.parse(s, formatter);
            endDate = LocalDate.parse(e, formatter);
            start = startDate.atStartOfDay(); // 开始时间：00:00:00
            end = endDate.atTime(23, 59, 59);
        } // 结束时间：23:59:59
        switch ( status){
            case "pending":
                status = "待执行";
                break;
            case "executed":
                status = "已执行";
                break;
            case "canceled":
                status = "已取消";
                break;
            default:
                status = null;
        }
        List<NursingOrderVO> nursingOrderVOList = nursingJobMapper.list(oldName, nurseName, item, start, end, status);
        nursingOrderVOList.forEach(nursingOrderVO -> {
           int i= (int) (Math.random()*10);
           if (i<5){
               nursingOrderVO.setItemType("护理计划内");
           }else {nursingOrderVO.setItemType("护理计划外");}
        });
        PageInfo<NursingOrderVO> pageInfo = new PageInfo<>(nursingOrderVOList);


        return pageInfo;
    }

    @Override
    public List<String> items() {
        List<String> items = nursingJobMapper.items();
        return items;
    }

    @Override
    public List<String> nurses() {
        List<String> nurses = nursingJobMapper.nurses();
        return nurses;
    }

    @Override
    public Integer cancel(NursingCancelDTO nursingCancelDTO) {
 int taId=nursingJobMapper.selectTaIdByOldNameAndItemName(nursingCancelDTO.getOldName(),nursingCancelDTO.getItemName());
 int i=nursingJobMapper.cancel(taId,nursingCancelDTO.getCancelTime(),nursingCancelDTO.getReason());
        return i;
    }

    @Override
    public NursingDetailDTO detail(String orderNo, String bedNo,String creator,String oldName) {
       String remark= nursingJobMapper.selectRemark(orderNo);
       NursingDetailDTO nursingDetailDTO=new NursingDetailDTO();
       nursingDetailDTO.setRemark(remark);
      NursingDetailDTO elderlyInfo= nursingJobMapper.selectElderlyInfo(bedNo,oldName);
      nursingDetailDTO.setSex(elderlyInfo.getSex());
      nursingDetailDTO.setAge(elderlyInfo.getAge());
  List<String> nursingNameList=nursingJobMapper.selectNursingNameList(elderlyInfo.getBedId());
        System.out.println("护理员名字列表"+nursingNameList);
        System.out.println("床位号"+elderlyInfo.getBedId());
  nursingDetailDTO.setNursingNameList(nursingNameList);
 String nursingLevel= nursingJobMapper.selectNursingLevel(creator);
 nursingDetailDTO.setNursingLevel(nursingLevel);
        return nursingDetailDTO;
    }

    @Override
    public int submitExecuteRecord(NursingExecuteRecord record, MultipartFile executeImage) {
        String uploadDir = "D:\\upload";
        File dir = new File(uploadDir);
        if (!dir.exists()) {
            boolean isDirCreated = dir.mkdirs();
            if (!isDirCreated) {
                throw new RuntimeException("上传目录创建失败，请检查路径权限：" + uploadDir);
            }
        }
        // 3. 生成唯一文件名（避免重复覆盖）
        String originalFileName = executeImage.getOriginalFilename();
        if (originalFileName == null || originalFileName.lastIndexOf(".") == -1) {
            throw new RuntimeException("无效的文件名，无法获取文件后缀");
        }
        // 获取文件后缀（如.jpg、.png）
        String fileSuffix = originalFileName.substring(originalFileName.lastIndexOf("."));
        // 生成UUID唯一文件名（例如：f47ac10b-58cc-4372-a567-0e02b2c3d479.jpg）
        String uniqueFileName = UUID.randomUUID().toString() + fileSuffix;
        // 4. 原生IO流写入文件到指定盘符
        String destFilePath = uploadDir + uniqueFileName;
        try (
                InputStream in = executeImage.getInputStream(); // 上传文件的输入流
                OutputStream out = new FileOutputStream(destFilePath) // 目标文件输出流
        ) {
            byte[] buffer = new byte[8192]; // 8KB缓冲区，平衡读写效率
            int bytesRead;
            // 循环读取输入流数据，写入到输出流（即保存到D盘）
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            out.flush(); // 强制刷新缓冲区，确保数据完全写入
        }catch (IOException e){
            throw new RuntimeException("上传文件失败：" + e.getMessage());
        }
        String imageUrl = "/upload/" + uniqueFileName;
        imageUrl = imageUrl.replace(File.separator, "/");
        record.setExecuteImageUrl(imageUrl);

        int i = nursingJobMapper.submitExecuteRecord(record);

        return i;
    }

    @Override
    public int reschedule(String oldName, String itemName, LocalDateTime expectTime) {
        int i=nursingJobMapper.reschedule(oldName,itemName,expectTime);
        return i;
    }


}
